/**
 * @author Luc Yriarte
 * 
 * Licence : BSD http://www.opensource.org/licenses/bsd-license.php
 *  
 */
package fractalViewer;

import java.applet.Applet;
import java.awt.Color;
import java.awt.Event;
import java.awt.Graphics;
import java.awt.Image;

import basicSim.ComplexPlan;

public class FractalViewerApplet extends Applet {
	int maxIterations, dragX, dragY, colormask;
	static double COMPLEX_PLAN_EXTENT = 4;
	static int MAX_ITERATIONS = 100;
	ComplexPlan plan;
	Image planImage;
	
	public FractalViewerApplet() {
		super();
	}
		
	public void init() {
		planImage = createImage(this.getSize().width,this.getSize().height);
		String str;
		str = getParameter("Extent");
		double ext = (str == null) ? COMPLEX_PLAN_EXTENT : new Double(str).doubleValue();
		str = getParameter("Iterations");
		maxIterations = (str == null) ? MAX_ITERATIONS : new Integer(str).intValue();
		str = getParameter("Color");
		if (str == null)
			colormask = 0;
		else if (str.equalsIgnoreCase("Red"))
			colormask = 0x00FF0000;
		else if (str.equalsIgnoreCase("Green"))
			colormask = 0x0000FF00;
		else if (str.equalsIgnoreCase("Blue"))
			colormask = 0x000000FF;		
		else if (str.equalsIgnoreCase("Cyan"))
			colormask = 0x0000FFFF;
		else if (str.equalsIgnoreCase("Magenta"))
			colormask = 0x00FF00FF;
		else if (str.equalsIgnoreCase("Yellow"))
			colormask = 0x00FFFF00;		
		
		plan = new ComplexPlan(Math.max(this.getSize().width,this.getSize().height), ext, -ext/2, -ext/2, planImage);
		plan.drawMandelbrot(maxIterations,colormask);
	}
	
	public void paint(Graphics g) {
		g.drawImage(planImage,0,0,null);
	}
	
	public boolean mouseDown(Event arg0, int arg1, int arg2) {
		dragX = arg1;
		dragY = arg2;
		return true;
	}

	public boolean mouseDrag(Event arg0, int arg1, int arg2) {
		Graphics g = this.getGraphics();
		g.drawImage(planImage,0,0,null);
		g.setColor(new Color(0xffffffff));
		g.drawRect(dragX,dragY,arg1-dragX,arg2-dragY);
		return true;
	}

	public boolean mouseUp(Event arg0, int arg1, int arg2) {
		Graphics g = this.getGraphics();
		int dragExtent = Math.max(arg1-dragX,arg2-dragY);
		g.drawImage(planImage,0,0,null);
		g.setColor(new Color(0));
		g.fillRect(dragX,dragY,dragExtent,dragExtent);
		double extX, extY = 0;
		extX = plan.cell[arg1][arg2].a - plan.cell[dragX][dragY].a;
		extY = plan.cell[arg1][arg2].b - plan.cell[dragX][dragY].b;
		plan = new ComplexPlan(Math.max(this.getSize().width,this.getSize().height), Math.max(extX,extY), 
				plan.cell[dragX][dragY].a, plan.cell[dragX][dragY].b, planImage);
		dragX = dragY = 0;
		plan.drawMandelbrot(maxIterations,colormask);
		repaint();
		return true;
	}


}
